/*
 * SimpleTest.java
 *
 * Created on 30 november 2005, 14:43
 */

package org.pereni.ctrl.demo;

import java.util.Timer;
import java.util.TimerTask;
import javax.comm.SerialPort;
import org.pereni.ctrl.Device;
import org.pereni.ctrl.DeviceImp;
import org.pereni.ctrl.DeviceRegister;
import org.pereni.ctrl.DeviceRegisterImp;
import org.pereni.ctrl.comm.ComControl;
import org.pereni.ctrl.comm.SerialComHandler;
import org.pereni.ctrl.comm.SerialParameters;
import org.pereni.ctrl.extras.MemoryMap;
import org.pereni.ctrl.extras.MemoryVariable;
//import org.pereni.ctrl.vend.omron.fins.command.MemmoryRead;
import org.pereni.ctrl.vend.omron.toolbus.ToolbusProtocol;
import org.pereni.ctrl.vend.omron.toolbus.commands.AreaReadDM;
import org.pereni.ctrl.vend.omron.toolbus.commands.AreaWriteDM;
import org.pereni.ctrl.vend.omron.toolbus.commands.MemoryRead;

/**
 *
 * @author  JanCarel
 */
public class SimpleTest_1 extends javax.swing.JFrame {
  
  /** Creates new form SimpleTest */
  public SimpleTest_1() {
    initSystem();
    initComponents();
    jLabel1.setText("--------------------------------------------------------");
    jLabel2.setText("--------------------------------------------------------");
    setTitle("Communications test with Omron PLC");
    setSize(800,800);
  }
  
  /** This method is called from within the constructor to
   * initialize the form.
   * WARNING: Do NOT modify this code. The content of this method is
   * always regenerated by the Form Editor.
   */
  // <editor-fold defaultstate="collapsed" desc=" Generated Code ">//GEN-BEGIN:initComponents
  private void initComponents() {
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();

    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jLabel1.setText("jLabel1");
    getContentPane().add(jLabel1, java.awt.BorderLayout.NORTH);

    jLabel2.setText("jLabel2");
    getContentPane().add(jLabel2, java.awt.BorderLayout.SOUTH);

    pack();
  }// </editor-fold>//GEN-END:initComponents
  
  /**
   * @param args the command line arguments
   */
  public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(new Runnable() {
      public void run() {
        new SimpleTest_1().setVisible(true);
      }
    });
  }
  
  public void initSystem(){
    
    plc = new DeviceImp(0, "CQM1", "Test PLC", "PLC for communications test");
    
    deviceRegister = DeviceRegisterImp.getInstance();
    deviceRegister.addDevice(plc);
    
    
    
    comHandler = new SerialComHandler(getPLCSerialParameters(), "PLCCON");
    
    if( comHandler instanceof ComControl) {
      ((ComControl)comHandler).setCommunicationTimeOut(10000);
    }
    
    comHandler.initialize();
    comHandler.setProtocolHandler(new ToolbusProtocol());
    comHandler.start();
    
    if(comHandler.isStarted()){
      //dataRead = new MemmoryRead(MemmoryRead.DM_WORD, 0, 10);
      //readData = new FinsProxy(plc, dataRead);
      readData = new AreaReadDM(plc, 0,20);
      Timer pingTimer = new Timer();
      pingTimer.schedule(new PingTask(), 1000 , 100 );
    }else{
      //no good without com port, show error
    }
    Timer secondTimer = new Timer();
    secondTimer.schedule(new SecondTask(), 1000, 1000);
  }
  
  public SerialParameters getPLCSerialParameters() {
    SerialParameters parameters = new SerialParameters();
    parameters.setPortName("COM4");
    //getLog().info("PLC Connecting on port: " + comPort);
    parameters.setBaudRate(19200);
    //getLog().info("PLC Connecting at speed: " + comSpeed);
    parameters.setParity(SerialPort.PARITY_EVEN);
    //getLog().info("PLC Parity: " + parameters.getParityString());
    parameters.setDatabits(SerialPort.DATABITS_7);
    //getLog().info("PLC Data Bits: " + parameters.getDatabitsString());
    parameters.setStopbits(SerialPort.STOPBITS_2);
    //getLog().info("PLC Stop Bits: " + parameters.getStopbitsString());
    return parameters;
  }
  
  
  class PingTask extends TimerTask {
    public void run() {
      // dataRead.clear();
      counter++;
      if (counter>65000){counter = 0;}
      long startT = System.currentTimeMillis();
      AreaWriteDM aw = new AreaWriteDM(plc);
      aw.setValue(5, new int[]{counter, counter+1});
      comHandler.send(aw);
      int[] ww = aw.getReply().toIntArray();
      
      comHandler.send(readData);
      
      
      
      //int[]dataBuff =readData.getReply().toIntArray();
      
      //System.out.println(" took time :: "+(System.currentTimeMillis()-startT));
      //DataImp di = new DataImp(dataBuff);
      
      MemoryMap.getInstance().process(readData, MemoryMap.HEX);
      int dm5 = MemoryMap.getInstance().getValue(new MemoryVariable("DM",5));
      jLabel2.setText("value dm 5 is "+dm5);
      //System.out.println(" data inp is "+di.toString());
      count = count + 2;
    }
  }
  
  class SecondTask extends TimerTask{
    public void run(){
      //System.out.println("count is "+count);
      jLabel1.setText("count is "+count);
      count = 0;
    }
  }
  // Variables declaration - do not modify//GEN-BEGIN:variables
  private javax.swing.JLabel jLabel1;
  private javax.swing.JLabel jLabel2;
  // End of variables declaration//GEN-END:variables
  //protected String        comPort = "COM3";
  //protected int          comSpeed = 57600;
  //protected boolean   updateOnMin = true;
  protected SerialComHandler comHandler = null;
  protected Device            plc = null;
  protected DeviceRegister deviceRegister;
  // protected FinsProxy  readData;
  protected AreaReadDM readData;
  protected MemoryRead  dataRead;
  private int counter;
  private int count;
}
